package zhoufu.sz.sanxiao_check.net;

import android.content.Context;
import android.util.Log;
import com.google.gson.Gson;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import zhoufu.sz.sanxiao_check.config.Constant;
import zhoufu.sz.sanxiao_check.protocol.ApiService;
import zhoufu.sz.sanxiao_check.utils.DESUtil;
import zhoufu.sz.sanxiao_check.utils.NetWorkUtil;
import zhoufu.sz.sanxiao_check.utils.StringConverterFactory;

/**
 * Created by h on 2016/6/20.
 *
 */
public   class RequestHelper {

    private ApiService _apiService;

    public interface RequestCallBack<T>{
        void onPullStart();
        void onPullFailud(Throwable throwable);
        void onPullEnd();
        void onPullSuccessed(T s);
    }
     final Context _Context;
    public RequestHelper(Context Context) {
        _Context = Context;
    }
    private OkHttpClient provideOkHttpClient(Context Context)
    {
        OkHttpClient client = new OkHttpClient();
        return client;
    }

    @Deprecated
    private OkHttpClient getCacheOkHttpClient(Context Context){
        return  new OkHttpClient().newBuilder().addInterceptor(CacheInterceptor(Context)).
                cache(CacheBuild(Context,"wxCache")).build();
    }

    private OkHttpClient getDesOkHttpClient(Context context){
        return new OkHttpClient().newBuilder().addInterceptor(DesInterceptor(context)).build();
    }

    private Cache CacheBuild(Context Context, String fileName)
    {
        File targetStore = new File(Context.getExternalCacheDir(), fileName);
        int   maxSize     = 1024 * 1024 * 10;// 10m
        return  new Cache(targetStore, maxSize);

    }

    /**
     *
     * @return 返回的内容是已经解密的 json 字符串
     */
    public ApiService provideApiService()
    {
        if (_apiService==null){
            Retrofit retrofit = new Retrofit.Builder().baseUrl(Constant.getWebService()).client(getDesOkHttpClient(_Context)).
                    /**
                     * Expected a string but was BEGIN_OBJECT at line 1 column 2 path $
                     * 需要将StringConverterFactory 放在前面。
                     */
                            addConverterFactory(StringConverterFactory.create()).
                            addConverterFactory(GsonConverterFactory.create()).
                            addCallAdapterFactory(RxJavaCallAdapterFactory.create()).
                            build();
            _apiService = retrofit.create(ApiService.class);
        }

        return _apiService;
    }

//    public static final String XMlURL = "http://120.31.131.190:8006";//外网

    /**
     *
     * @return 返回的内容是已经解密的 json 字符串
     */
    public ApiService setPassService( )
    {
        Retrofit retrofit = new Retrofit.Builder().baseUrl("http://120.31.131.190:8006").client(getDesOkHttpClient(_Context)).
                /**
                 * Expected a string but was BEGIN_OBJECT at line 1 column 2 path $
                 * 需要将StringConverterFactory 放在前面。
                 */
                        addConverterFactory(StringConverterFactory.create()).
                        addConverterFactory(GsonConverterFactory.create()).
                        addCallAdapterFactory(RxJavaCallAdapterFactory.create()).
                        build();
        return retrofit.create(ApiService.class);
    }

    private Interceptor DesInterceptor(final Context context){
        return new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Response     response     = chain.proceed(chain.request());
                ResponseBody responseBody = response.body();
                String       result    = responseBody.string();
                //String       result1[]    = resultXml.split("\n");
                //String       result       = result1[1]
                //        .substring(result1[1].indexOf('>') + 1, result1[1].lastIndexOf('<'));
                result = Constant.isEncrypt() ? DESUtil.decryptDoNet(result) : result;//解密
                Log.e("Client", "intercept#result:" + result);
                ResponseBody newResponseBody = ResponseBody.create(responseBody.contentType(), result);
                Response     newResponse     = response.newBuilder().body(newResponseBody).build();
                return newResponse;
            }
        };
    }
    private Interceptor CacheInterceptor(final Context Context)
    {
        return new Interceptor()
        {
            @Override public Response intercept(Chain chain) throws IOException
            {
                // 拿到 数据
                Response response = chain.proceed(chain.request());
                //根据当前的 网络状况来 决定数据来源
                if ( NetWorkUtil.isNetWorkAvailable(Context))
                {
                    int maxSeconds = 60*60*5;//5min
                    return response.newBuilder().removeHeader("Pragma")
                            .removeHeader("Cache-Control")
                            .addHeader("Cache-Control", "Public , max-age = " + maxSeconds)
                            .build();
                } else
                {
                    int maxTime = 3600 * 12;//12fenzhong
                    return response.newBuilder().removeHeader("Pragma")
                            .removeHeader("Cache-Control")
                            .addHeader("Cache-Control",
                                    "Public , only-if-cached, max-age = " + maxTime)
                            .build();
                }
            }
        };
    }

    /**
     * 加密Map
     */
    private static Map<String, Object> encryptMap(Map<String, Object> map)
    {
        String json           = new Gson().toJson(map);
        String encryptContent = DESUtil.encryptAsDoNet(json);
        map.clear();
        Log.e("RequestHelper", "encryptMap start:" + json);
        map.put("json", encryptContent);
        Log.e("RequestHelper", "encryptMap end:" + encryptContent);
        return map;
    }
}
